package com.microtf.wx.control;

import com.microtf.wx.server.BaiduAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;


@Controller()
@RequestMapping("/upload")
public class Upload {
    @Value("${web.attachement.dir}")
    String attachmentDir;
    @Autowired
    BaiduAPI baiduAPI;

    @RequestMapping("/index")
    public ModelAndView uploadIndex(ModelAndView modelAndView) {
        modelAndView.addObject("uploadPath", attachmentDir);
        return modelAndView;
    }

    @PostMapping(value = "/upload", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "uuid", required = false) String uuid) {
        String fileName = attachmentDir + "/" + file.getOriginalFilename();
        try {
            file.transferTo(new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String picInfo = baiduAPI.getPicInfo(fileName);
        return picInfo;
    }
}
